/*
 * @Descripttion: 实现context
 * @Author: lukasavage
 * @Date: 2021-12-30 21:21:28
 * @LastEditors: lukasavage
 * @LastEditTime: 2021-12-30 22:55:37
 */

import { Component } from './component2';
import {
	REACT_ELEMENT,
	REACT_FORWARD_REF,
	REACT_CONTEXT,
	REACT_PROVIDER,
} from './constants';
import { wrapToVDOM } from './utils';

function createElement(type, config, children) {
	let key = null,
		ref = null;
	if (config) {
		key = config.key;
		ref = config.ref;
		delete config.ref;
		delete config.key;
		delete config.__source;
		delete config.__self;
	}
	const props = { ...config };
	if (arguments.length > 3) {
		props.children = Array.prototype.slice
			.call(arguments, 2)
			.map(wrapToVDOM);
	} else if (arguments.length === 3) {
		props.children = wrapToVDOM(children);
	}

	return {
		$$typeof: REACT_ELEMENT,
		key,
		ref,
		type,
		props,
	};
}
function createRef() {
	return { current: null };
}
function forwardRef(render) {
	return {
		$$typeof: REACT_FORWARD_REF,
		render,
	};
}
/* ---------------实现context---------- */

function createContext() {
	const context = { $$typeof: REACT_CONTEXT, _currentValue: undefined };
	// 这里给context塞属性
	context.Provider = {
		$$typeof: REACT_PROVIDER,
		_context: context,
	};
	context.Consumer = {
		$$typeof: REACT_CONTEXT,
		_context: context,
	};

	return context;
}

/*
let context = {
    $$typeof: Symbol(react.context),
    Consumer: {$$typeof: Symbol(react.context), _context: context},    // ☆ 注意这里循环引用
    Provider: {$$typeof: Symbol(react.provider), _context: context},
    _currentValue: {xxx: xxx}
}



*/

const react = {
	createElement,
	Component,
	createRef,
	forwardRef,
    createContext
};

export default react;
